package com.mnt.washio.utils.network.ws;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;

import com.mnt.washio.objects.Coupon;
import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.NetworkUtils;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;

@SuppressLint("SimpleDateFormat")
public class GetCouponWSControl extends BaseWSControl {
	String userId;
	
	public GetCouponWSControl(Context context,
			WebServiceCommunicatorListener listener, String userId) {
		super(context, listener, WebServiceFlag.GET_COUPON);
		this.userId = userId;
	}

	@Override
	protected Object doInBackground(Void... params) {
		// Get local database

		String url = Statics.WASHIO_WS_URL + "coupon/user/"
				+ userId;
		try {
			String respone = NetworkUtils.doRequest(url);
			return getCoupon(respone);

		} catch (ClientProtocolException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		} catch (IOException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		}
		return null;
	}

	@SuppressLint("DefaultLocale")
	private Coupon getCoupon(String json) {
		try {
			JSONObject jsonObject = new JSONObject(json);
			if(jsonObject.has("error")){
				mError = jsonObject.getString("error");
				return null;
			}
			if (jsonObject.has("coupon")) {
				JSONObject couponJsonObject = jsonObject
						.getJSONObject("coupon");
				Coupon coupon = new Coupon();
				coupon.setId(couponJsonObject.getString("objectId"));
				coupon.setAmmount(couponJsonObject.getInt("amount"));
				coupon.setCode(couponJsonObject.getString("code").toUpperCase());
				coupon.setDurationId(couponJsonObject.getJSONObject("duration")
						.getString("objectId"));
				coupon.setActive(couponJsonObject.getBoolean("isActive"));
				coupon.setPercent(couponJsonObject.getBoolean("isPercent"));
				coupon.setMaxRedemption(couponJsonObject
						.getInt("maxRedemptions"));
				coupon.setRedemptionLeft(couponJsonObject
						.getInt("redemptionsLeft"));
				coupon.setTypeId(couponJsonObject.getJSONObject("type")
						.getString("objectId"));
				coupon.setEndDate(parseDate(couponJsonObject.getJSONObject(
						"endDate").getString("iso")));
				coupon.setStartDate(parseDate(couponJsonObject.getJSONObject(
						"startDate").getString("iso")));
				coupon.setDateCreated(parseDate(couponJsonObject
						.getString("createdAt")));
				coupon.setDateUpdated(parseDate(couponJsonObject
						.getString("updatedAt")));
				return coupon;
			}
			return null;
		} catch (Exception e) {
			mError = e.getMessage();
			return null;
		}
	}

}
